import 'dart:math';

import 'package:flutter/material.dart';

class PageWindowModel {
  Widget child;
  Offset offset;
  PageWindowModel({required this.offset, required this.child});
}

class PageWindowContainer extends StatelessWidget {
  const PageWindowContainer({
    super.key,
    required this.page,
    required this.windows,
  });
  final List<PageWindowModel> windows;
  final Widget page;
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Stack(
          children: List.generate(windows.length, (i) {
            final m = windows[i];
            return PageWindow(
              bottom: m.offset.dy,
              right: m.offset.dx,
              biggestSize: constraints.biggest,
              child: m.child,
            );
          })
            ..insert(0, page),
        );
      },
    );
  }
}

class PageWindow extends StatefulWidget {
  const PageWindow({
    super.key,
    required this.child,
    required this.biggestSize,
    this.bottom = 20,
    this.right = 10,
  });
  final Widget child;
  final double bottom;
  final double right;
  final Size biggestSize;
  @override
  State<PageWindow> createState() => _PageWindowState();
}

class _PageWindowState extends State<PageWindow> {
  Size? _size;
  Offset? _orign;
  Offset? _position;

  Offset moveStart = Offset.zero;
  final GlobalKey childKey = GlobalKey();

  @override
  void initState() {
    _orign = Offset(widget.right, widget.bottom);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final bs = widget.biggestSize;
    return Positioned(
        bottom: _position?.dy ?? _orign?.dy,
        right: _position?.dx ?? _orign?.dx,
        key: childKey,
        child: SafeArea(
          child: GestureDetector(
              onPanStart: (details) {
                moveStart = details.localPosition;
                final box =
                    childKey.currentContext?.findRenderObject() as RenderBox?;

                _orign = box?.localToGlobal(Offset.zero);
                _size = box?.size;
              },
              onPanUpdate: (details) {
                if (_orign == null) {
                  return;
                }
                var x = details.localPosition.dx - moveStart.dx;
                var y = details.localPosition.dy - moveStart.dy;

                _position = Offset(
                    min(max(0, bs.width - (_orign!.dx + x + _size!.width)),
                        bs.width - _size!.width),
                    max(
                      min(bs.height - _size!.height,
                          bs.height - (_orign!.dy + y + _size!.height)),
                      0,
                    ));

                setState(() {});
              },
              child: widget.child),
        ));
  }
}
